package com.example.dingdong.rest;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.dingdong.FilePath;
import com.example.dingdong.daomain.AdminEntity;
import com.example.dingdong.daomain.BasicUserEntity;
import com.example.dingdong.daomain.RoleEntity;
import com.example.dingdong.enumerate.RoleTypeEnum;
import com.example.dingdong.repository.AdminRepository;
import com.example.dingdong.repository.BasicUserRepository;
import com.example.dingdong.repository.RoleRepository;
import com.example.dingdong.service.BasicUserService;
import com.example.dingdong.service.RoleService;
import com.example.dingdong.util.CheckRequestUtil;
import com.example.dingdong.util.ExceptionType;
import com.example.dingdong.util.FileUploadUtil;
import com.example.dingdong.util.MyException;

/**
 * 
 * @ClassName: UserRest
 * @Description: 用户rest层
 * @Author :chengwenixng
 * @DateTime 2021-08-02 16:17:56
 */
@RestController
@RequestMapping("/web/rest/user/")
public class BasicUserRest {
	//创建日志
	private static final Logger log = LoggerFactory.getLogger(BasicUserRest.class);

	@Autowired
	private BasicUserService userService;
	@Autowired
	private BasicUserRepository userRepository;
	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private RoleService roleService;
	@Autowired
	AdminRepository adminRepository;
	/**
	 * 
	 * @Title: login
	 * @Description: 登录
	 * @Author coding
	 * @DateTime 2021-08-04 15:29:21
	 * @param reqStr
	 * @param request
	 * @return
	 */
	@RequestMapping("login")
	public JSONObject login(@RequestBody String reqStr, HttpServletRequest request) {
		log.info("login 登录:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "login");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "login");
			// 获取登录名
			if (req.get("account") == null) {
				throw new MyException(ExceptionType.NotFound, "缺少account字段！");
			}
			String account = req.getString("account");
			// 获取输入密码
			if (req.get("password") == null) {
				throw new MyException(ExceptionType.NotFound, "缺少password字段！");
			}
			
			//判断是否
			BasicUserEntity basicUserEntity=userRepository.findByAccountAndDelFlag(account, true);
			if(basicUserEntity.getRoleEntity().getRoleName().equals("Admin") && basicUserEntity.getAdminEntity().getAuthorization() == false) {
				throw new MyException(ExceptionType.NotFound, "该账号为管理员账号，未授权！");
			}
			
			String password = req.getString("password");
			// 获取登陆人员的IP
			String remoteIp = request.getRemoteAddr();
			// 登陆
			userService.login(account, password, remoteIp);
			BasicUserEntity user = userService.getLoginUser();
			response.put("roleId", user.getRoleEntity() != null ? user.getRoleEntity().getId() : "");
			response.put("roleName", user.getRoleEntity() != null ? user.getRoleEntity().getRoleName() : "");
			response.put("res", true);
		} catch (MyException e) {
			log.error("login:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("login:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @Title: registered
	 * @Description: 账号注册
	 * @Author coding
	 * @DateTime 2021-08-04 14:39:53
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("registered")
	public JSONObject registered(@RequestBody String reqStr) {
		log.info("registered:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "registered");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "registered");
			/**
			 * 获取前端数据
			 */
			// 获取账号角色
			if (req.get("role") == null) {
				throw new MyException("缺少role字段！");
			}
			String role = req.getString("role");
			// 获取账号
			if (req.get("account") == null) {
				throw new MyException("缺少account字段！");
			}
			// 获取密码
			if (req.get("password") == null) {
				throw new MyException("缺少password字段！");
			}
			//判断账号类型
			RoleTypeEnum typeEnum = RoleTypeEnum.valueOf(role);
			if (typeEnum == null) {
				throw new Exception("请确认填写用户类型是否正确!");
			}
			req.put("typeId", typeEnum.ordinal());
			//开始注册
			userService.getUser(req);
			response.put("res", true);
		} catch (MyException e) {
			log.error("registered:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("registered:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @Title: isLogin
	 * @Description: 获取登录状态
	 * @Author coding
	 * @DateTime 2021-08-04 15:21:30
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("isLogin")
	public JSONObject isLogin(@RequestBody String reqStr) {
		log.info("isLogin 获取登录状态:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "isLogin");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			CheckRequestUtil.checkReqInterface(reqStr, "isLogin");
			// 获取登陆状态
			boolean flag = userService.isLogin();
			response.put("res", flag);
		} catch (Exception e) {
			log.error("isLogin:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("isLogin 接口方法调用完成" + return_data);
		return return_data;
	}
	/**
	 * 
	 * @Title: logout
	 * @Description: 注销账号
	 * @Author coding
	 * @DateTime 2021-08-04 15:22:59
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("logout")
	public JSONObject logout(@RequestBody String reqStr) {
		log.info("logout:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "logout");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			CheckRequestUtil.checkReqInterface(reqStr, "logout");
			//注销账号
			 userService.logout();
			 response.put("res", true);
			}catch(MyException e) {
				log.error("logout:" + e.getReason());
				response.put("res", false);
				response.put("exception", e.getReason());
			}catch(Exception e) {
				log.error("logout:" + e.getMessage());
				response.put("res", false);
				response.put("exception", e.getMessage());
			}
			return return_data;

	}
	/**
	 * 
	 * @Title: modifyUserHeadPortrait
	 * @Description: 修改用户头像
	 * @Author coding
	 * @DateTime 2021-08-09 17:12:48
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("modifyUserHeadPortrait")
	public JSONObject modifyUserHeadPortrait(@RequestBody String reqStr) {
		log.info("modifyUserHeadPortrait:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "modifyUserHeadPortrait");
		returnData.put("type", "response");
		returnData.put("response", response);
		
		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "modifyUserHeadPortrait");
			 
			// 获取当前登录的用户
			BasicUserEntity basicUserEntity = userService.getLoginUser();
			
			String headPortraitPath = req.getString("headPortraitPath");
			if(headPortraitPath == null) {
				throw new MyException(ExceptionType.NotFound, "缺少头像路径！");
			}
			/**
			 * 先判断缓存文件夹里面有没有相关的图片文件
			 */
			File cachePictureFile = new File(headPortraitPath);
			if (!cachePictureFile.exists()) {
				throw new MyException(ExceptionType.NotFound, "暂无该缓存图片，请重新上传文件后添加！");
			}
			
			String entityDir = FilePath.BASICUSER_PATH + "/" + basicUserEntity.getId();
			File entityDirFile = new File(entityDir);
			if (!entityDirFile.exists()) {
				boolean flag = entityDirFile.mkdirs();
				if (!flag) {
					throw new MyException(ExceptionType.OperationError, "创建文件夹失败，请重新添加！");
				}
			}
			// 获取源文件名
			String[] strArr = headPortraitPath.split("\\/");
			String sourceFileName = strArr[strArr.length - 1];
			// 新文件路径
			String picturePath = entityDir + "/" + System.currentTimeMillis() + "_" + sourceFileName;
			// 复制文件
			boolean copyFlag = FileUploadUtil.copyFile(headPortraitPath, picturePath);
			if (!copyFlag) {
				throw new MyException(ExceptionType.OperationError, "复制文件失败，请重新添加！");
			}
			basicUserEntity.setHeadPicturePath(picturePath);
			userService.startSavaBasicUserEntity(basicUserEntity);
			response.put("res", true);
		} catch (MyException e) {
			log.error("modifyUserHeadPortrait:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("modifyUserHeadPortrait:");
			e.printStackTrace();
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		System.out.println("modifyUserHeadPortrait调用完成:" + returnData);
		return returnData;
	}
	/**
	 * 
	 * @Title: editPassword
	 * @Description: 根据手机号找回密码
	 * @Author coding
	 * @DateTime 2021-06-04 13:44:59
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("editPassword")
	public JSONObject editPassword(@RequestBody String reqStr) {
		log.info("registered:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "editPassword");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "editPassword");
			/**
			 * 获取前端数据
			 */
			// 获取账号
			if (req.get("account") == null) {
				throw new MyException("缺少account字段！");
			}
			// 获取密码
			if (req.get("password") == null) {
				throw new MyException("缺少password字段！");
			}
			//修改密码
			userService.editPassword(req);
			response.put("res", true);
		} catch (MyException e) {
			log.error("editPassword:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("editPassword:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @Title: alterPassword
	 * @Description: 修改密码
	 * @Author coding
	 * @DateTime 2021-06-04 13:44:59
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("alterPassword")
	public JSONObject alterPassword(@RequestBody String reqStr) {
		log.info("registered:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "alterPassword");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "alterPassword");
			/**
			 * 获取前端数据
			 */
			// 获取账号
			if (req.get("oldPassword") == null) {
				throw new MyException("缺少oldPassword字段！");
			}
			String oldPassword = req.getString("oldPassword");

			// 获取密码
			if (req.get("password") == null) {
				throw new MyException("缺少password字段！");
			}
			String password = req.getString("password");

			BasicUserEntity basicUserEntity = userService.getLoginUser();
			if(basicUserEntity.getPassword().equals(oldPassword)) {
				//保存数据
				basicUserEntity.setPassword(password);
				//修改密码
				userService.startSavaBasicUserEntity(basicUserEntity);
			}else {
				throw new MyException("旧密码填写错误!");
			}
			
			
			response.put("res", true);
		} catch (MyException e) {
			log.error("alterPassword:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("alterPassword:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @Title: findBasicData
	 * @Description:获取所有用户 
	 * @Author coding
	 * @DateTime 2021-08-06 20:31:48
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("findBasicData")
	public JSONObject findBasicData(@RequestBody String reqStr) {
		log.info("findBasicData:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "findBasicData");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			CheckRequestUtil.checkReqInterface(reqStr, "findBasicData");
			// 获取数据
			List<BasicUserEntity> basicUserEntities = userService.getAllBasicUserDatas();
			JSONArray adminData = new JSONArray();
			JSONArray otherUserData = new JSONArray();
			basicUserEntities.forEach((user) ->{
				JSONObject addData = new JSONObject();
				addData.put("id", user.getId()); // id值
				addData.put("key", user.getId()); // key值
				addData.put("account", user.getAccount()); // 用户账号
				addData.put("password", user.getPassword()); // 用户账号
				addData.put("phone", user.getPhone()); // 手机号
				addData.put("role", user.getRoleEntity().getRoleName()); // 用户角色
				addData.put("remarks", user.getRoleEntity().getRemark()); // 
				addData.put("authorization", user.getAdminEntity()!=null ?  user.getAdminEntity().getAuthorization() : ""); // 是否授权
				if (RoleTypeEnum.Admin.equals(RoleTypeEnum.valueOf(user.getRoleEntity().getRoleName()))) {
					adminData.add(addData);
				}else {
					otherUserData.add(addData);
				}
			 });
			/**
			 * 返回前端数据
			 */
			response.put("res", true);
			response.put("adminDatas", adminData);
			response.put("otherUserData",otherUserData);		
		}catch (MyException e) {
			log.error("findBasicData:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("findBasicData:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		System.out.println(response.toJSONString());
		System.out.println("findBasicData接口方法调用完成");
		return return_data;
	}
	/**
	 * 
	 * @Title: deleteBasicData
	 * @Description: 删除用户
	 * @Author coding
	 * @DateTime 2021-08-06 21:09:19
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("deleteBasicData")
	public JSONObject deleteBasicData(@RequestBody String reqStr) {
		log.info("deleteBasicData:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "deleteBasicData");
		returnData.put("type", "response");
		returnData.put("response", response);
		
		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "deleteBasicData");
			
			List<Object> idList = request.getJSONArray("idList");
			if (idList == null || idList.size() == 0) {
				throw new MyException(ExceptionType.NotFound, "请传入idList！");
			}

			/**
			 * 查找数据库中的数据
			 */
			for (Object object : idList) {
				BasicUserEntity basicUserEntity =userService.getBasicUserEntity(Long.valueOf(String.valueOf(object)).longValue(), true);
				if  ( basicUserEntity == null) {
					throw new MyException(ExceptionType.LookupDatabaseIsEmpty, "数据库中暂无该数据！");
				}
				if(basicUserEntity.getAccount().equals("admin")) {
					throw new Exception("账号admin为系统创建用户，不可删除！");
				}
				/**
				 * 删除数据
				 */
				 basicUserEntity.setDelFlag(false);
				userService.startSavaBasicUserEntity(basicUserEntity);
			}
			
			/**
			 * 返回数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("deleteBasicData:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("deleteBasicData:");
			e.printStackTrace();
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("deleteBasicData: " + returnData);
		System.out.println("deleteBasicData接口方法调用完成");
		return returnData;
	}
	/**
	 * 
	 * @Title: personalCenter
	 * @Description: 获取当前用户的基本信息
	 * @Author coding
	 * @DateTime 2021-08-09 13:49:39
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("personalCenter")
	public JSONObject personalCenter(@RequestBody String reqStr) {
		log.info("获取当前用户信息:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "personalCenter");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			CheckRequestUtil.checkReqInterface(reqStr, "personalCenter");
			// 获取当前登录的用户
			BasicUserEntity basicUserEntity = userService.getLoginUser();
			// 账号密码
			JSONObject addData = new JSONObject();
			JSONArray data = new JSONArray();
			addData.put("id", basicUserEntity.getId() != null ? basicUserEntity.getId() : 0); // id值
			addData.put("key", basicUserEntity.getId() != null ? basicUserEntity.getId() : 0); // key值
			addData.put("address", basicUserEntity.getAddress()); 
			addData.put("account", basicUserEntity.getAccount() != null ? basicUserEntity.getAccount() : ""); // 密码
			addData.put("password", basicUserEntity.getPassword() != null ? basicUserEntity.getPassword() : ""); // 账号
			addData.put("headPortraitPath", basicUserEntity.getHeadPicturePath() != null ?basicUserEntity.getHeadPicturePath() : ""); // 头像
			addData.put("userName", basicUserEntity.getUserName() != null ? basicUserEntity.getUserName(): "暂无"); //用户名称
			addData.put("phone", basicUserEntity.getPhone() != null ?  basicUserEntity.getPhone() : "暂无"); // 手机号
			data.add(addData);			
			/**
			 * 返回前端数据
			 */
			response.put("res", true);
			response.put("message", addData);
		} catch (MyException e) {
			log.error("personalCenter:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("personalCenter:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("personalCenter 接口方法调用完成!");
		return return_data;
	}
	
	/**
	 * 
	 * @Title: startAuthorization
	 * @Description: 最高管理员授权其它管理员登录
	 * @Author coding
	 * @DateTime 2021-08-07 14:04:50
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("startAuthorization")
	public JSONObject startAuthorization(@RequestBody String reqStr) {
		log.info("registered:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "startAuthorization");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "startAuthorization");
			// 获取id
			if ( req.get("id") == null) {
				throw new MyException("缺少id 字段！");
			}
			Long id = req.getLong("id");
			//判断是否为admin最高管理圆账号
			BasicUserEntity user = userService.getLoginUser();
			if(user.getAccount().equals("admin")) {
				//查询该管理员
				BasicUserEntity basicUserEntity=userService.getBasicUserEntity(id, true);
				if( basicUserEntity== null) {
					throw new Exception("不存在数据库");
				}
				//开始授权
				AdminEntity adminEntity=basicUserEntity.getAdminEntity();
				adminEntity.setAuthorization(!adminEntity.getAuthorization());
				adminRepository.save(adminEntity);
			}else {
				throw new MyException("该账号暂无权限!");
			}
			
			response.put("res", true);
		} catch (MyException e) {
			log.error("startAuthorization:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("startAuthorization:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @throws Exception 
	 * @Title: addAdmin
	 * @Description: 创建系统高级管理员
	 * @Author coding
	 * @DateTime 2021-08-06 20:55:53
	 */
	public void addAdmin(){
		AdminEntity adminEntity = new AdminEntity();
		BasicUserEntity basicUserEntity = userRepository.findByAccountAndDelFlag("admin", true);
		if (basicUserEntity == null) {
			basicUserEntity = new BasicUserEntity();
			basicUserEntity.setAccount("admin");
			basicUserEntity.setPassword("admin");
			basicUserEntity.setAdminEntity(adminEntity);
			adminEntity.setAuthorization(true);
			userRepository.save(basicUserEntity);
			adminRepository.save(adminEntity);
			RoleEntity role = roleService.getRoleByName("Admin", true);	
			basicUserEntity.setRoleEntity(role);
			userRepository.save(basicUserEntity);
		}	
		
	}
	/**
	 * @Title: addRole
	 * @Description: 创建角色
	 * @Author coding
	 * @DateTime 2021-08-06 19:29:36
	 */
	public void addRole() {	
		RoleEntity adminRole = roleService.getRoleByName("Admin", true);
		if (adminRole == null) {
			adminRole = new RoleEntity();
		}
		adminRole.setRoleName("Admin");
		adminRole.setRemark("管理员");
		roleRepository.save(adminRole);	
		
		RoleEntity bosslordRole = roleService.getRoleByName("Boss", true);
		if ( bosslordRole  == null) {
			 bosslordRole  = new RoleEntity();
		}
		 bosslordRole .setRoleName("Boss");
		 bosslordRole .setRemark("老板");
		roleRepository.save(  bosslordRole );	
		
		RoleEntity ClientRole = roleService.getRoleByName("Client", true);
		if (ClientRole == null) {
			ClientRole = new RoleEntity();
		}
		ClientRole .setRoleName("Client");
		ClientRole .setRemark("客户");
		roleRepository.save(ClientRole );	  
	}
	
}
